import 'package:flutter/material.dart';
import 'package:ichinesereader/models/student/Assignments.dart';
import 'package:ichinesereader/pages/student/homeworkDetailedBooks.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import '../../themes/pageStyles.dart';

// ignore: must_be_immutable
class HomeworkRecordsDataGrid extends StatelessWidget {
  HomeworkRecordsDataGrid(this.assignments);

  List<Assignment> assignments;

  bool isWebOrDesktop = GetPlatform.isWeb || GetPlatform.isDesktop;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssignmentRecordsDataGrid---');

    return Column(children: [
      Expanded(child: _buildDataGrid()),
    ]);
  }

  Container _buildDataGrid() {
    return Container(
      //  margin: _pageStyles.gridEdgeInsets(),
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source: AssignmentRecordsDataGridSource(items: assignments),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          allowSorting: true,
          allowFiltering: true,
          allowTriStateSorting: true,
          allowSwiping: false,
          controller: _dataGridController,
          navigationMode: GridNavigationMode.row,
          columns: <GridColumn>[
            GridColumn(
              width: isWebOrDesktop ? 240 : 180,
              columnName: 'Title',
              label: buildDataGridColumnLabel('Title'),
            ),
            GridColumn(
              columnName: 'Status',
              //allowFiltering: false,
              width: isWebOrDesktop ? 160 : 150,
              label: buildDataGridColumnLabel('Status'),
            ),
            GridColumn(
              columnName: 'RequiredReadings',
              allowFiltering: false,
              width: isWebOrDesktop ? 220.0 : 190.0,
              label: buildDataGridColumnLabel('RequiredReadings'),
            ),
            GridColumn(
              columnName: 'Progress',
              allowFiltering: false,
              width: isWebOrDesktop ? 160 : 160,
              label: buildDataGridColumnLabel('Progress'),
            ),
            GridColumn(
              columnName: 'Lang',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Lang'),
            ),
            GridColumn(
              columnName: 'Language',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Language'),
            ),
            GridColumn(
              columnName: 'DueDate',
              allowFiltering: false,
              width: 180,
              label: buildDataGridColumnLabel('DueDate'),
            ),
            GridColumn(
              columnName: 'StartDate',
              allowFiltering: false,
              width: 180,
              label: buildDataGridColumnLabel('StartDate'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
          ],
        ),
      ),
    );
  }
}

class AssignmentRecordsDataGridSource extends DataGridSource {
  AssignmentRecordsDataGridSource({required List<Assignment> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'Title', value: dataGridRow.assignment?.name),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.assignment?.status?.toUpperCase() ?? ''),
              DataGridCell<int>(
                  columnName: 'RequiredReadings',
                  value: dataGridRow.assignment?.noOfBookToBeRead),
              DataGridCell<int>(
                columnName: 'Progress',
                value: dataGridRow.overallProgress,
              ),
              DataGridCell<String>(
                columnName: 'Lang',
                value: dataGridRow.assignment?.settings!.lang ?? 'Mandarin',
              ),
              DataGridCell<String>(
                columnName: 'Language',
                value:
                    dataGridRow.assignment?.settings!.language ?? 'Simplified',
              ),
              DataGridCell<int>(
                columnName: 'DueDate',
                value: dataGridRow.assignment?.endDateUtc,
                // value: DateTime.fromMillisecondsSinceEpoch(
                //     dataGridRow.endDateUtc as int,
                //     isUtc: true),
              ),
              DataGridCell<int>(
                columnName: 'StartDate',
                value: dataGridRow.assignment?.startDate,
                // value: DateTime.fromMillisecondsSinceEpoch(
                //     dataGridRow.startDate as int),
              ),
              DataGridCell<String>(
                  columnName: 'Id', value: dataGridRow.assignment?.id),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'CreateDate' ||
              dataGridCell.columnName == 'StartDate' ||
              dataGridCell.columnName == 'DueDate') {
            if (dataGridCell.value != null && dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.fade,
                    style: Get.textTheme.bodySmall?.copyWith(
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Colors.blueGrey),
                  ));
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '',
                    overflow: TextOverflow.fade,
                  ));
            }
          } else if (dataGridCell.columnName == 'Title') {
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: GestureDetector(
                onTap: () {
                  var assignmentId = row
                      .getCells()
                      .where((element) => element.columnName == 'Id')
                      .first
                      .value;
                  var lang = row
                      .getCells()
                      .where((element) => element.columnName == 'Lang')
                      .first
                      .value;
                  var language = row
                      .getCells()
                      .where((element) => element.columnName == 'Language')
                      .first
                      .value;
                  Get.to(() =>
                      HomeworkDetailedBooks(assignmentId, lang, language));
                },
                child: Text(
                  dataGridCell.value.toString(),
                  style: Get.theme.textTheme.titleLarge,
                  overflow: TextOverflow.fade,
                ),
              ),
            );
          } else if (dataGridCell.columnName == 'Progress') {
            int process = dataGridCell.value ?? 0;
            return Container(
              child: LinearPercentIndicator(
                animation: true,
                lineHeight: 18.0,
                animationDuration: 1000,
                percent: process.toDouble() / 100,
                center: Text(
                  "$process%",
                  style: TextStyle(color: Colors.black),
                ),
                progressColor: Get.isDarkMode
                    ? Get.theme.primaryColorDark
                    : Get.theme.primaryColor,
                barRadius: Radius.circular(16),
                backgroundColor: AppTheme.colors.disableBtnLight,
              ),
            );
          } else {
            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall?.copyWith(
                      color: Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : Colors.blueGrey),
                ));
          }
        }).toList());
  }
}
